import time
from datetime import datetime, timedelta
from flask import render_template, request, current_app, session, redirect, url_for, g, jsonify

from info import constants, db
from info.models import User, News, Category
from info.modules.admin import admin_blu
from info.utils.common import query_user_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@admin_blu.route("/news_type", methods=['POST', 'GET'])
def news_type():
    """
    新闻分类的模板展示
    新闻分类的修改和添加
    :return:
    """
    if request.method == "GET":

        try:
            categories = Category.query.all()
        except Exception as f:
            current_app.logger.error(f)
            return render_template("admin/news_edit_detail.html", errmsg="数据查询错误")

        category_dict_li = []
        for category in categories:
            category_li = category.to_dict()
            category_dict_li.append(category_li)

        # 删除最新分类
        category_dict_li.pop(0)
        data = {
            "category_dict_li": category_dict_li
        }

        return render_template("admin/news_type.html", data=data)

    # 修改分类
    # 1 获取参数

    cid = request.json.get("id")
    cname = request.json.get("name")

    # 判断参数
    if not cname:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if cid:
        # 有分类id代表查询
        try:
            cid = int(cid)
            category = Category.query.get(cid)
        except Exception as f:
            current_app.logger.error(f)
            return jsonify(errno=RET.DBERR, errmsg="未查询到此分类")

        if not category:
            return jsonify(errno=RET.NODATA, errmsg="没有此列新闻")

        category.name = cname
    else:
        category = Category()
        category.name = cname
        db.session.add(category)
    return jsonify(errno=RET.OK, errmsg="操作成功")


@admin_blu.route('/news_edit_detail', methods=['POST', 'GET'])
def news_edit_detail():
    """
    审核新闻详情的数据页面加载
    :return:
    """
    if request.method == "GET":
        # 1 请求参数
        news_id = request.args.get("news_id")

        # 2 验证参数
        try:
            news_id = int(news_id)
        except Exception as f:
            current_app.logger.error(f)
            return render_template("admin/news_edit_detail.html", errmsg="参数错误")
        try:
            news = News.query.get(news_id)
        except Exception as f:
            current_app.logger.error(f)
            return render_template("admin/news_edit_detail.html", errmsg="参数错误")
        if not news:
            return render_template("admin/news_edit_detail.html", errmsg="没查询到这条新闻")

        # 查询新闻分类

        try:
            categories = Category.query.all()
        except Exception as f:
            current_app.logger.error(f)
            return render_template("admin/news_edit_detail.html", errmsg="数据查询错误")

        category_dict_li = []
        for category in categories:
            category_li = category.to_dict()
            if category.id == news.category_id:
                category_li["is_selected"] = True
            category_dict_li.append(category_li)

        # 删除最新分类
        category_dict_li.pop(0)
        data = {
            "news": news.to_dict(),
            "category_dict_li": category_dict_li
        }

        return render_template("admin/news_edit_detail.html", data=data)

    # 修改新闻内容

    # 1 获取参数
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image_url = request.files.get("index_image")
    category_id = request.form.get("category_id")

    # 判断参数
    try:
        news_id = int(news_id)
        category_id = int(category_id)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not news:
        return jsonify(errno=RET.DATAERR, errmsg="新闻不存在")

    # 先读取图片
    if index_image_url:
        try:
            index_image_url = index_image_url.read()
        except Exception as f:
            current_app.logger.error(f)
            return jsonify(errno=RET.DATAERR, errmsg="图片读取失败")
        # 保存图片
        try:
            key = storage(index_image_url)
        except Exception as f:
            current_app.logger.error(f)
            return jsonify(errno=RET.DATAERR, errmsg="图片读取失败")
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

    # 初始化新闻
    news.digest = digest
    news.content = content
    news.category_id = category_id
    news.title = title

    return jsonify(errno=RET.OK, errmsg="操作成功")


@admin_blu.route('/news_edit')
def news_edit():
    """
    新闻版式编辑列表界面实现
    :return:
    """
    # 1 获取参数
    page = request.args.get("page", 1)
    keywords = request.args.get('keywords', None)

    # 检验参数
    try:
        page = int(page)
    except Exception as f:
        current_app.logger.error(f)
        page = 1

    filters = [News.status == 0]
    # 如果有搜索关键字, 把搜索条件添加到搜索语句
    if keywords:
        filters.append(News.title.contains(keywords))
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                          constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                          False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as f:
        current_app.logger.error(f)

    news_list = []
    for news in news_li:
        news_list.append(news.to_review_dict())

    context = {
        "news_list": news_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template('admin/news_edit.html', data=context)


@admin_blu.route('/new_review_active', methods=['POST'])
def new_review_active():
    """
    新闻审核通过,或不通过,还有原因
    :return:
    """
    # 1 获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2 检验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3 查询新闻
    try:
        news = News.query.get(news_id)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.DBERR, errmsg="没查询到新闻")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    if action == "accept":
        # 审核通过, 数据库中status 变为0
        news.status = 0
    else:
        # 审核不通过, 获取审核不通过的理由参数
        reason = request.json.get("reason")

        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="请说出未通过理由")

        # 不通过理由存到数据库, 还有status
        news.reason = reason
        news.status = 1

    return jsonify(errno=RET.OK, errmsg="操作成功")


@admin_blu.route('/news_review_detail/<int:news_id>')
def new_review_detail(news_id):
    """
     审核新闻是否通过

    :param news_id:
    :return:
    """
    # 通过数据库查询出这条新闻
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as f:
        current_app.logger.error(f)
        return render_template('admin/news_review_detail.html', errmsg="未查询到此新闻")
    data = {
        "news": news.to_dict()
    }

    return render_template('admin/news_review_detail.html', data=data)


@admin_blu.route('/news_review')
def news_review():
    """
    新闻待审核列表数据显示
    :return:
    """
    # 1 获取参数
    page = request.args.get("p", 1)
    # 新闻审核列表的搜索功能
    keywords = request.args.get("keywords", None)

    # 2, 校验参数
    try:
        page = int(page)
    except Exception as f:
        current_app.logger.error(f)
        page = 1
    # 3, 数据库查询
    news_li = []
    current_page = 1
    total_page = 1

    filters = [News.status != 0]
    # 获取关键字搜索
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(
            News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as f:
        current_app.logger.error(f)

    news_list = []
    for news in news_li:
        news_list.append(news.to_review_dict())

    context = {
        "news_list": news_list,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("admin/news_review.html", data=context)


@admin_blu.route('/user_list')
def user_list():
    """
    用户列表
    :return:
    """
    # 　1 获取参数
    page = request.args.get("page", 1)

    # 2, 检验参数
    try:
        page = int(page)
    except Exception as f:
        current_app.logger.error(f)
        page = 1
    # 数据库查询数据
    users = []
    total_page = 1
    current_page = 1
    try:
        paginate = User.query.filter(User.is_admin == False, ).order_by(User.last_login.desc()).paginate(page,
                                                                                                         constants.USER_COLLECTION_MAX_NEWS,
                                                                                                         False)
        users = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as f:
        current_app.logger.error(f)

    users_dict_li = []
    for user in users:
        users_dict_li.append(user.to_admin_dict())

    data = {
        "users_dict_li": users_dict_li,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("admin/user_list.html", data=data)


@admin_blu.route('/user_count')
def user_count():
    """
     用户统计

    :return:
    """
    # 用户总数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as f:
        current_app.logger.error(f)

    # 用户月新增数
    mon_count = 0
    t = time.localtime()
    mon_begin = '%d-%02d-01' % (t.tm_year, t.tm_mon)
    mon_begin_data = datetime.strptime(mon_begin, "%Y-%m-%d")
    try:
        mon_count = User.query.filter(User.is_admin == False, User.create_time > mon_begin_data).count()
    except Exception as f:
        current_app.logger.error(f)

    # 用户日新增用户
    day_count = 0
    t = time.localtime()
    mon_begin = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    mon_begin_data = datetime.strptime(mon_begin, "%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > mon_begin_data).count()
    except Exception as f:
        current_app.logger.error(f)

    # 活跃时间
    active_time = []
    # 活跃用户
    active_count = []
    mon_begin = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    begin_today_data = datetime.strptime(mon_begin, "%Y-%m-%d")
    # begin_today_data = datetime.strptime('%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday), "%Y-%m-%d")
    count = None
    for i in range(30):
        begin_data = begin_today_data - timedelta(days=i)
        end_data = begin_today_data - timedelta(days=(i - 1))
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_data,
                                      User.last_login <= end_data).count()
        except Exception as f:
            current_app.logger.error(f)
        active_count.append(count)
        active_time.append(begin_data.strftime("%Y-%m-%d"))

    active_time.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_count": active_count,
        "active_time": active_time

    }
    return render_template('admin/user_count.html', data=data)


@admin_blu.route('/index')
@query_user_data
def index():
    user = g.user
    return render_template('admin/index.html', user=user.to_dict())


@admin_blu.route('/login', methods=["POST", "GET"])
def login():
    if request.method == "GET":
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)

        if user_id and is_admin:
            return redirect(url_for("admin.index"))
        return render_template("admin/login.html")

    # 1 获取参数
    username = request.form.get("username")
    password = request.form.get("password")

    # 校验参数
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数不足")

    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as f:
        current_app.logger.error(f)
        return render_template("admin/login.html", errmsg="用户信息查询失败")

    if not user:
        return render_template("admin/login.html", errmsg="用户信息不存在")

    if not user.check_password(password):
        return render_template("admin/login.html", errmsg="密码错误")

    # 往 session 中保存数据表示当前已登录
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name
    session["is_admin"] = user.is_admin

    return redirect(url_for("admin.index"))
